let configuration = require('../../../configuration');

class ErrorMsg {
    constructor(text, timeout) {
        this.text = text;
        this.timeout = timeout;
        let maxAnimationTime = 0.2 * 1000;
        this.animationTime = timeout / 4 > maxAnimationTime ? maxAnimationTime : timeout / 4;
        this.start = Date.now();
    }

    init(initConfig) {
        this.componentContainer = initConfig.componentContainer;
        setTimeout(() => {
            this.componentContainer.removeComponent(this);
        }, this.timeout);
    }

    includesPoint() {
        return true;
    }

    draw(canvas) {
        let ctx = canvas.getContext('2d');
        let windowWidth = configuration.get('window.width');
        let windowHeight = configuration.get('window.height');
        let msgWidth = configuration.get('components.sys.errorMsg.width');
        let msgHeight = configuration.get('components.sys.errorMsg.height');

        let percentage = (Date.now() - this.start) / this.animationTime;
        let actualHeight = percentage > 1 ? msgHeight : msgHeight * percentage;

        ctx.beginPath();
        ctx.fillStyle = 'silver';
        ctx.strokeStyle = 'black';
        ctx.rect(windowWidth / 2 - msgWidth / 2, windowHeight / 2 - msgHeight / 2, msgWidth, actualHeight);
        ctx.fill();
        ctx.stroke();

        ctx.clip();
        ctx.fillStyle = 'black';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.font = '40px 微软雅黑';
        ctx.fillText(this.text, windowWidth / 2, windowHeight / 2);
    }
}

module.exports = ErrorMsg;
